package com.ycrlkj.android.modulescore.main.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ToastUtils;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.ycrlkj.android.modulescore.main.apiservice.DictValueApiService;
import com.ycrlkj.android.modulescore.main.entity.DictValue;
import com.ycrlkj.android.modulescore.main.entity.validate.VehicleValidate;
import com.ycrlkj.android.modulespublic.common.base.MArrayAdapter;
import com.ycrlkj.android.modulespublic.common.net.exception.ApiException;
import com.ycrlkj.android.modulespublic.common.net.exception.ApiExceptionHandler;
import com.ycrlkj.android.modulespublic.common.net.exception.ErrorConsumer;
import com.ycrlkj.android.modulespublic.common.net.response.ResultData;
import com.ycrlkj.android.modulespublic.common.net.transformer.ResponseTransformer;
import com.ycrlkj.android.modulescore.main.apiservice.VehicleApiService;
import com.ycrlkj.android.modulescore.main.databinding.ActivityVehicleEditBinding;
import com.ycrlkj.android.modulescore.main.entity.Vehicle;
import com.ycrlkj.android.modulescore.main.viewmodel.VehicleViewModel;
import com.ycrlkj.android.modulespublic.common.constant.RoutePath;
import com.ycrlkj.android.modulespublic.common.utils.xpopup.XPopupUtil;
import com.ycrlkj.android.modulespublic.common.widget.titlebar.MTitleBar;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import dagger.hilt.android.AndroidEntryPoint;
import io.reactivex.functions.Consumer;

@AndroidEntryPoint
@Route(path = RoutePath.PAGE_VEHICLE_EDIT)
public class VehicleEditActivity extends AppCompatActivity {

    private ActivityVehicleEditBinding binding;

    private VehicleViewModel viewModel;

    @Inject
    VehicleApiService vehicleApiService;

    @Inject
    DictValueApiService dictValueApiService;

    @Autowired
    String id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ARouter.getInstance().inject(this);

        if(id == null && id.length() != 19){
            XPopupUtil.showAlert(this, "未找到车辆信息, 关闭页面", new OnConfirmListener() {
                @Override
                public void onConfirm() {
                    VehicleEditActivity.this.finish();
                }
            });
        }

        binding = ActivityVehicleEditBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        viewModel = new ViewModelProvider(this).get(VehicleViewModel.class);

        binding.setLifecycleOwner(this);

        initTitleBar();

        get();
    }

    @SuppressLint("CheckResult")
    public void save(View view) {
        Vehicle form = viewModel.getVehicle().getValue();

        //校验表单
        String msg = VehicleValidate.validateForm(form);
        if(msg != null){
            ToastUtils.showLong(msg);
            return;
        }

        LoadingPopupView loadingPopupView = XPopupUtil.showLoading(this, "正在提交...");
        XPopupUtil.hideLoadingDelay(loadingPopupView);

        vehicleApiService.edit(form)
                .compose(ResponseTransformer.obtain())
                .subscribe(new Consumer<ResultData>() {
                    @Override
                    public void accept(ResultData resultData) throws Exception {
                        XPopupUtil.hideLoading(loadingPopupView);
                        XPopupUtil.showAlert(VehicleEditActivity.this, resultData.getToast());
                    }
                }, new ErrorConsumer() {
                    @Override
                    protected void error(ApiException e) {
                        XPopupUtil.hideLoading(loadingPopupView);
                        ApiExceptionHandler.doWith(VehicleEditActivity.this, e);
                    }
                });
    }

    public void initTitleBar() {

        MTitleBar mTitleBar = binding.mTitleBar;

        mTitleBar.setBtnEvents(new MTitleBar.BtnEvents() {
            @Override
            public void setBtnLeftOnClickListener() {
                VehicleEditActivity.this.finish();
            }

            @Override
            public void setBtnRightOnClickListener() {
            }
        });
    }


    @SuppressLint("CheckResult")
    public void get() {
        LoadingPopupView loadingPopupView = XPopupUtil.showLoading(this, "正在提交...");
        XPopupUtil.hideLoadingDelay(loadingPopupView);
        vehicleApiService.getById(id)
                .compose(ResponseTransformer.obtain())
                .subscribe(new Consumer<Vehicle>() {
                    @Override
                    public void accept(Vehicle vehicle) throws Exception {
                        XPopupUtil.hideLoading(loadingPopupView);

                        viewModel.getVehicle().setValue(vehicle);
                        binding.setViewModel(viewModel);

                        //初始化Spinner
                        initSpinnerSpecification();
                        initSpinnerPlateColor();
                        initSpinnerBuyTime();

                    }
                }, new ErrorConsumer() {
                    @Override
                    protected void error(ApiException e) {
                        XPopupUtil.hideLoading(loadingPopupView);
                        ApiExceptionHandler.doWith(VehicleEditActivity.this, e);
                    }
                });
    }

    @SuppressLint("CheckResult")
    public void initSpinnerSpecification() {

        Spinner spinner = binding.spinnerSpecification;

        dictValueApiService.getAllByDictFieldName("vehicle_specification")
                .compose(ResponseTransformer.obtain())
                .subscribe(new Consumer<List<DictValue>>() {
                    @Override
                    public void accept(List<DictValue> dictValues) throws Exception {

                        String[] names = new String[dictValues.size() + 1];
                        Integer[] values = new Integer[dictValues.size() + 1];

                        for (int i = 0; i < dictValues.size() + 1; i++) {
                            if (i == 0) {
                                names[i] = "请选择";
                                values[i] = -1;
                            }else{
                                String name = dictValues.get(i-1).getText();
                                names[i] = name;
                                Integer value = dictValues.get(i-1).getValue();
                                values[i] = value;
                            }
                        }

                        MArrayAdapter<String> spinnerAdapter = new MArrayAdapter<>(VehicleEditActivity.this, android.R.layout.simple_spinner_item, names);
                        //设置下拉列表的风格
                        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        //添加adapter到spinner
                        spinner.setAdapter(spinnerAdapter);

                        /* #region ========================= 设置默认值 开始 ====================== */
                        Integer value = viewModel.getVehicle().getValue().getSpecification();
                        if (value != null){
                            for(int i=0; i<values.length; i++){
                                if(values[i] == value){
                                    spinner.setSelection(i, true);
                                }
                            }
                        }
                        /* #endregion ====================== 设置默认值 结束 ====================== */

                        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                viewModel.getVehicle().getValue().setSpecification(values[position]);
                                binding.setViewModel(viewModel);
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {
                                //选择从此视图中消失时调用的回调方法。例如: 当触控激活或适配器变空时，选择可能会消失
                                //父项现在不包含选定项的AdapterView
                            }
                        });
                    }
                }, new ErrorConsumer() {
                    @Override
                    protected void error(ApiException e) {
                        ApiExceptionHandler.doWith(VehicleEditActivity.this, e);
                    }
                });
    }

    @SuppressLint("CheckResult")
    public void initSpinnerPlateColor() {

        Spinner spinner = binding.spinnerPlateColor;

        dictValueApiService.getAllByDictFieldName("vehicle_plate_color")
                .compose(ResponseTransformer.obtain())
                .subscribe(new Consumer<List<DictValue>>() {
                    @Override
                    public void accept(List<DictValue> dictValues) throws Exception {

                        String[] names = new String[dictValues.size() + 1];
                        Integer[] values = new Integer[dictValues.size() + 1];

                        for (int i = 0; i < dictValues.size() + 1; i++) {
                            if (i == 0) {
                                names[i] = "请选择";
                                values[i] = -1;
                            }else{
                                String name = dictValues.get(i-1).getText();
                                names[i] = name;
                                Integer value = dictValues.get(i-1).getValue();
                                values[i] = value;
                            }
                        }

                        MArrayAdapter<String> spinnerAdapter = new MArrayAdapter<>(VehicleEditActivity.this, android.R.layout.simple_spinner_item, names);
                        //设置下拉列表的风格
                        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        //添加adapter到spinner
                        spinner.setAdapter(spinnerAdapter);

                        /* #region ========================= 设置默认值 开始 ====================== */
                        Integer value = viewModel.getVehicle().getValue().getPlateColor();
                        if (value != null){
                            for(int i=0; i<values.length; i++){
                                if(values[i] == value){
                                    spinner.setSelection(i, true);
                                }
                            }
                        }
                        /* #endregion ====================== 设置默认值 结束 ====================== */

                        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                viewModel.getVehicle().getValue().setPlateColor(values[position]);
                                binding.setViewModel(viewModel);
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {
                                //选择从此视图中消失时调用的回调方法。例如: 当触控激活或适配器变空时，选择可能会消失
                                //父项现在不包含选定项的AdapterView
                            }
                        });
                    }
                }, new ErrorConsumer() {
                    @Override
                    protected void error(ApiException e) {
                        ApiExceptionHandler.doWith(VehicleEditActivity.this, e);
                    }
                });
    }

    @SuppressLint({"CheckResult", "SimpleDateFormat"})
    public void initSpinnerBuyTime() {

        Spinner spinner = binding.spinnerBuyTime;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        String thisYear = String.valueOf(Integer.parseInt(sdf.format(new Date())) + 1);

        String[] values = new String[21];

        for(int i=0; i<21; i++){
            if(i == 0){
                values[i] = "请选择";
            }else{
                values[i] = String.valueOf(Integer.parseInt(thisYear) - i);
            }
        }

        MArrayAdapter<String> spinnerAdapter = new MArrayAdapter<>(VehicleEditActivity.this, android.R.layout.simple_spinner_item, values);
        //设置下拉列表的风格
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //添加adapter到spinner
        spinner.setAdapter(spinnerAdapter);

        /* #region ========================= 设置默认值 开始 ====================== */
        String value = viewModel.getVehicle().getValue().getBuyTime();
        if (value != null){
            for(int i=0; i<values.length; i++){
                if(values[i].equals(value)){
                    spinner.setSelection(i, true);
                }
            }
        }
        /* #endregion ====================== 设置默认值 结束 ====================== */

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                viewModel.getVehicle().getValue().setBuyTime(values[position]);
                binding.setViewModel(viewModel);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                //选择从此视图中消失时调用的回调方法。例如: 当触控激活或适配器变空时，选择可能会消失
                //父项现在不包含选定项的AdapterView
            }
        });
    }

}